'use client';

import { type ChangeEvent, type FormEvent, useEffect, useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { updateUserBasicInfo } from '@/services/api';
import type { TBody } from '@/types';
import type {
  IDifference,
  IUpdateUserBasicInfoBody,
  IUser,
} from '@/interfaces';
import diff from 'microdiff';
import useToast from '@/hooks/useToast';
import { getDiffData, getFilterData, isEmpty } from '@/lib/tool';

export default function UpdateUserInfo({ details }: { details: IUser }) {
  const [form, setForm] = useState<{
    alias?: string;
    username?: string;
    phone?: string;
    email?: string;
  }>({
    alias: '',
    username: '',
    phone: '',
    email: '',
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const { show } = useToast();

  const updateUserBasicInfoMutation = useMutation(
    async (variables: TBody<IUpdateUserBasicInfoBody>) => {
      await updateUserBasicInfo(variables);
    },
  );

  useEffect(() => {
    if (details) {
      setForm({
        alias: details.alias || '',
        username: details.username || '',
        phone: details.phone || '',
        email: details.email || '',
      });
    }
  }, [details]);
  useEffect(() => {
    if (details) {
      const differences = diff(
        {
          alias: details.alias || '',
          username: details.username || '',
          phone: details.phone || '',
          email: details.email || '',
        },
        form,
      );
      setDifferenceData(differences);
    }
  }, [form, details]);

  function onChangeForm(e: ChangeEvent<HTMLInputElement>) {
    const name = e.target.name;
    const value = e.target.value;
    setForm({ ...form, [name]: value });
  }

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      const body = getFilterData(getDiffData(differenceData));
      if (isEmpty(body)) {
        show({
          type: 'SUCCESS',
          message: '保存完成',
        });
        return;
      }

      await updateUserBasicInfoMutation.mutateAsync({
        id: details.id,
        data: body,
      });

      clearData();
      show({
        type: 'SUCCESS',
        message: '保存完成',
      });
    } catch (e) {
      updateUserBasicInfoMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function clearData() {
    setDifferenceData([]);
  }

  return (
    <div className="row">
      <div className="col">
        <form onSubmit={onClickSave} className="vstack gap-4">
          <div>
            <label className="form-label">别名</label>
            <input
              type="text"
              className="form-control"
              name="alias"
              value={form.alias}
              onChange={onChangeForm}
              aria-describedby="alias"
              placeholder="请输入别名"
            />
          </div>

          <div>
            <label className="form-label">用户名</label>
            <input
              type="text"
              className="form-control"
              name="username"
              value={form.username}
              onChange={onChangeForm}
              aria-describedby="username"
              placeholder="请输入用户名，长度最小 3，最大 16"
            />
          </div>

          <div>
            <label className="form-label">手机号</label>
            <input
              type="tel"
              className="form-control"
              name="phone"
              value={form.phone}
              onChange={onChangeForm}
              aria-describedby="phone"
              placeholder="请输入手机号"
            />
          </div>

          <div>
            <label className="form-label">电子邮箱</label>
            <input
              type="email"
              className="form-control"
              name="email"
              value={form.email}
              onChange={onChangeForm}
              aria-describedby="email"
              placeholder="请输入电子邮箱"
            />
          </div>

          <button
            type="submit"
            disabled={updateUserBasicInfoMutation.isLoading}
            className="btn btn-success w-25 my-4"
          >
            {updateUserBasicInfoMutation.isLoading && (
              <span
                className="spinner-border spinner-border-sm me-2"
                role="status"
                aria-hidden="true"
              ></span>
            )}
            更新
          </button>
        </form>
      </div>
    </div>
  );
}
